package algorithm.leetcode;


import java.util.HashMap;
import java.util.Map;

/**
 * Created by chengxiaoqi1 on 2018/6/28.
 */
public class TwoNum {
//    Given an array of integers, return indices of the two numbers such that they add up to a specific target.
//
//    You may assume that each input would have exactly one solution, and you may not use the same element twice.
//    Example:
//    Given nums = [2, 7, 11, 15], target = 9,
//
//    Because nums[0] + nums[1] = 2 + 7 = 9,
//            return [0, 1].


    public static void main(String[] args) {
        int[] arr = {2, 7, 11, 15};
        int target = 9;
        twoSum(arr, target);

    }

    public static int[] twoSum(int[] nums, int target) {
        int a = 0;
        int b = 0;
        int aIndex = 0;
        int bIndex = 0;
        for (int i = 0; i < nums.length; i++) {
            a = nums[i];
            aIndex = i;
            for (int j = i + 1; j < nums.length; j++) {
                b = nums[j];
                if (a + b == target) {
                    bIndex = j;
                    return new int[]{aIndex, bIndex};
                }
            }
        }
        return new int[]{0};
    }

    public int[] twoSum2(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }

        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement) && map.get(complement) != i) {
                return new int[]{i, map.get(complement)};
            }
        }

        return new int[]{0};
    }


}
